package com.sytech.power_bank.helper

val hexString = "0123456789ABCDEF".toCharArray()

fun String.hexToByte(): ByteArray {
    val arr = this.toCharArray()
    var bys = ByteArray(arr.size / 2)
    for (i in 0..arr.size - 1 step 2) {
        var b = 0
        var k = 0
        var c1 = arr[i];
        var c2 = arr[i + 1]
        hexString.forEachIndexed { index, c ->
            if (c == c1) {
                b = b or (index shl 4)
                k++
            }
            if (c == c2) {
                b = b or index
                k++
            }
            if (k == 2) {
                return@forEachIndexed
            }
        }
        bys[i / 2] = b.toByte()
    }
    return bys
}

fun ByteArray.toHexString(): String {
    var buf = CharArray(this.size * 2)
    var k = 0
    var b2 = 0x0f
    this.forEach {
        val f = it.toInt() and 0x00ff
        buf[k++] = hexString[(f ushr 4)]
        buf[k++] = hexString[(f and b2)]
    }
    return String(buf)
}

